<template>
  <div class="visitor_statistics">

    <div class="tips">
      操作说明
      <a-tooltip placement="right">
        <template #title>
          <span>提供最新访客的来源、访问轨迹、地域、客户端等详细信息。助您了解当前的访客行为，及时根据访客特征优化网站。</span>
        </template>
        <span class="iconfont icon-hint1"></span>
      </a-tooltip>
    </div>
    <div class="selectSite">
      <getSite @handleChange="handleChange" ref="getSite_ref"></getSite>
    </div>
    <div class="visitDetail">
      <div class="visitDetail_header">

        <div class="timeSelect item">
          <!-- 所属时间模块部分 -->
          <commonDatePick :formData='formData' @select-type="selectType" @selectTimeChange="selectTimeChange" ref="commonDatePick_ref"></commonDatePick>
        </div>
        <div class="from item" v-if="isOpen">
          <span>来源：</span>
          <a-select v-model:value="formData.fromSectionValue" placeholder="请选择"
            :options="formData.fromSectionOption.map((item: any) => ({ value: item.value, label: item.label }))"
            @change="handleChange"></a-select>
        </div>
        <div class="area item" v-if="isOpen">
          <getArea @handleChange="handleChange" ref="getArea_ref">
          </getArea>
        </div>
        <div class="visitorTypeSelect item" v-if="isOpen">
          <!-- 所属访客类型模块部分 -->
          <section class="options">
            <span class="options_label">访客:</span>
            <div class="options_content">
              <span v-for="item in formData.selectVisitorTypeOption" :key="item.value"
                :class="formData.selectVisitorType === item.value ? 'activeOption' : ''"
                @click="selectType(item, 'selectVisitorType')">{{
                  item.label
                }}</span>
            </div>
          </section>
        </div>
        <div class="option-content">
          <!-- <a-button @click="resetOptions">重置</a-button> -->
          <!-- <a-button :style="{ 'margin-right': '8px' }" class="addButton" type="primary" @click="">搜索</a-button> -->
          <div class="openorclose" @click="() => isOpen = true" v-if="!isOpen">
            <a>展开</a>
            <i class="iconfont icon-down" style="font-size: 24px"> </i>
          </div>
          <div class="openorclose" @click="() => isOpen = false" v-if="isOpen">
            <a>收起</a>
            <i class="iconfont icon-up" style="font-size: 24px"> </i>
          </div>
        </div>
      </div>
      <div class="tendency_statistics_charts">
        <div class="scrollSection">
          <div class="charts">
            <div class="pv_uvlists">
              <a-tabs v-model:activeKey="activeKey" @change="selectType">
                <a-tab-pane key="1" tab="访问页数"></a-tab-pane>
                <a-tab-pane key="2" tab="访问时长" force-render></a-tab-pane>
              </a-tabs>
            </div>
            <div class="pv_uvlists">
              <div class="pv_uvlists_item">
                <div>访问次数
                  <a-tooltip placement="right">
                    <template #title>
                      <span>访客访问您网站的次数，一个访客可以多次访问网站，一次访问可能会浏览多个页面。</span>
                    </template>
                    <span class="iconfont icon-hint1"></span>
                  </a-tooltip>

                </div>
                <div>{{ dataSource_remote.visitsTotalNum }}</div>
              </div>
            </div>
            <div class="tendencyOnlinePie_line">
              <div id="chart_loyalty_bar"></div>
            </div>
          </div>
          <!-- 表格展示部分 -->
          <baseTable :columns="loyaltyStatictics" :dataSource="configData.records" :isSelect="true" :scroll="scroll"
            ref="sensitiveBaseTables" :isShowPagination="isShowPagination" :rowSelection="1" :total="configData.total"
            :indentSize="60">
            <template #bodyCell="{ column, text, record }">
              <template v-if="column.ellipsis">
                <table-tool-tip :text="text" :column="column"></table-tool-tip>
              </template>
            </template>
          </baseTable>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, nextTick, onMounted, onBeforeMount, onUnmounted, reactive, watch, computed } from "vue";
import request from "@/api/index";
import getters from "@/store/getters";
import { initEcharts } from "@/components/echarts/index";
import { optionBar } from "./echartType/options";
import columns from "@/components/table/tableConfig/tableColumn/siteStatistics";
import { getTableScroll } from "@/components/table/tableConfig/table";
import baseTable from "@/components/table/baseTable.vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import commonDatePick from '../commonHeader/date.vue';
import getSite from '../commonHeader/getSite.vue';
import getArea from '../commonHeader/area.vue';
import { transverterMss } from '@/utils/common';
// type flowColumns
interface dataSourceType {
  [propName: string]: any;
}
//getters
const userInfo = getters.userInfo();
//data
const sectionValue = ref(userInfo.siteId);
const loyaltyStatictics = ref(JSON.parse(JSON.stringify(columns.loyaltyStatictics)));
const activeKey = ref('1');
const dataSource = ref<dataSourceType>(JSON.parse(JSON.stringify(optionBar)));
dataSource.value.legend.data = ['移动设备', '计算机'];

const showOptionsSelected = ref(1);
const showOptions = ref(
  [
    { label: '浏览量(PV)', value: 1 },
    { label: '访问数(UV)', value: 2 },
    { label: 'IP数', value: 3 },
  ]
);
const isOpen = ref(false);
const getSite_ref = ref();
//图表展示

const commonDatePick_ref = ref();
let selectTimeRange = ref<(string | number)[]>([]); //选择时间范围
let seleType_label = ref('pvTypeTypeNumDto');
const dataSource_remote = ref<dataSourceType>({})
//表格数据
let configData = reactive<dataSourceType>({ total: 0, size: 10, records: [] });
let scroll: dataSourceType = reactive({ y: 200, isFixed: false }); // 表单滚动设置
const isShowPagination = false; // 是否需要配分页器
let timeDuration = ['0-10秒', '10-30秒', '30-60秒', '1-3分钟', '3-10分钟', '10-20分钟', '21分钟以上'];
let pageDuration = ['1-2页', '3-5页', '6-8页', '9-11页', '12-20页', '20-50页', '51页以上'];

const formData = reactive<dataSourceType>({
  fromSectionValue: '', //来源
  fromSectionOption: [
    {
      label: '全部',
      value: ''
    }, {
      label: '搜索引擎',
      value: 1
    }, {
      label: '外部链接',
      value: 2
    }, {
      label: '直接访问',
      value: 3
    },
  ],
  selectTimeOption: 1,
  TimeOptions: [{
    label: '今天',
    value: 1
  }, {
    label: '昨天',
    value: 2
  }, {
    label: '最近7天',
    value: 3
  }, {
    label: '最近30天',
    value: 4
  }],
  selectVisitorType: '',
  selectVisitorTypeOption: [
    {
      label: '全部',
      value: ''
    }, {
      label: '新访客',
      value: 0
    }, {
      label: '老访客',
      value: 1
    },
  ],
})
let selectAreaData = ref(null); // 选择区域
const getArea_ref = ref();


// computed
selectAreaData = computed(() => getArea_ref.value?.selectAreaData || null);
seleType_label = computed(() => showOptionsSelected.value == 1 ? 'pvTypeTypeNumDto' :
  showOptionsSelected.value == 2 ? 'uvTypeTypeNumDto' : 'ipTypeTypeNumDto')
//methods
const handleChange = (value: any) => {//其他选择变化
  nextTick(() => {
    getVisitDuration();
  });
};
const selectTimeChange = () => {
  selectTimeRange.value = commonDatePick_ref.value.selectTimeRange;
  getVisitDuration();
}
// 获取在线统计数据
const getVisitDuration = async () => {
  sectionValue.value = getSite_ref.value.sectionValue;
  selectTimeRange.value = commonDatePick_ref.value.selectTimeRange;
  nextTick(async () => {
    let data: dataSourceType = {
      siteId: sectionValue.value,
      startTime: selectTimeRange.value[0],
      endTime: selectTimeRange.value[1],
      province: selectAreaData.value,
      sourceUrlType: formData.fromSectionValue,
      newVisitor: formData.selectVisitorType
    }
    let api = activeKey.value == '1' ? 'getAccessedPagesNumber' : 'getVisitDuration'
    await request[api](data).then((res: dataSourceType) => {
      dataSource_remote.value = res;
      let arr = activeKey.value == '1' ? pageDuration : timeDuration;
      configData.records = res.excelNumDtoList;
      configData.records.forEach((item: dataSourceType) => {
        item.duration = arr[item.index - 1];
        item.percentage = item.percentage !== '' ? item.percentage + '%' : '0%';
      });

    });
    nextTick(() => {
      setData()
    })
  })
}
//选择搜索项
const selectType = (item: dataSourceType, type: string) => {
  formData[type] = item.value;
  loyaltyStatictics.value[1].title = activeKey.value == '1' ? '访问页面' : '访问时长';
  nextTick(() => {
    getVisitDuration();
  })
}
const setData = () => {
  let res = dataSource_remote.value;
  let name = activeKey.value == '1' ? '访问次数' : '访问时长';
  dataSource.value.xAxis[0].data = activeKey.value == '1' ? pageDuration : timeDuration;
  dataSource.value.series = [{
    name: name,
    type: 'bar',
    barWidth: '40',
    data: res.indexNumDtoList.map((item: dataSourceType) => item.num),
  }]
  initEcharts('chart_loyalty_bar', dataSource.value);
}


//onMounted

onMounted(() => {
  getVisitDuration();

});

</script>

<style lang="less" scoped>
.visitor_statistics {
  width: 100%;
  height: calc(100% - 72px);
  padding: 16px;
  background: #fff;
  overflow: auto;

  .tips {
    margin-bottom: 24px;
    font-size: 14px;
    color: #333;
  }

  .visitDetail {
    .visitDetail_header {
      display: flex;
      flex-wrap: wrap;
      position: relative;
      width: 90%;
      padding-top: 24px;

      .from {
        font-size: 14px;
        color: #333;
      }

      .timeSelect {
        margin-right: 24px;
      }

      .item {
        height: 40px;
        margin-right: 24px;
        margin-bottom: 24px;
      }

      .ant-select {
        width: 100px;
      }

      .option-content {
        position: absolute;
        right: -10%;
        display: flex;
        top: 18px;
        align-items: center;
        font-size: 14px;
      }
    }

    .charts {
      width: 100%;
      height: 350px;
      border: 1px solid #e8e8e8;
      border-radius: 4px;
      padding: 24px;
      margin-bottom: 24px;
      padding-top: 0px;

      #chart_loyalty_bar {
        width: 100%;
        height: 300px;
      }

      .pv_uvlists_item {
        margin-top: 12px;
      }
    }
  }
}
</style>
<style lang="scss">
.visitDetail {
  .options {
    display: flex;
    align-items: center;
    font-size: 14px;

    .options_label {
      margin-right: 12px;
    }

    .options_content {
      margin-right: 12px;
      border: 1px solid var(--theme_button_bg_color, #1F6DED);
      display: flex;
      border-radius: 4px;

      span {
        padding: 4px 14px;
        color: #333;
        border-right: 1px solid var(--theme_button_bg_color, #1F6DED);
      }

      span:nth-last-of-type(1) {
        border-right: none;
      }

      span:hover {
        background: var(--theme_button_hover_bg_color, #4892fa);
        border-color: var(--theme_button_hover_bg_color, #4892fa);
        color: #fff;
      }

      .activeOption {
        color: #fff;
        background: var(--theme_button_bg_color, #1F6DED);
      }
    }
  }

  .pv_uvlists_item {
    margin-top: 12px;
  }
}
</style>
<style lang="scss">
.visitor_statistics {
  .ant-table-thead .ant-table-cell:nth-last-of-type(1) {
    text-align: left;
    margin-right: 16px;
  }

  .ant-table-cell {
    .ant-table-row-expand-icon {
      border: none;
      background: transparent;
    }
  }

  .ant-table-expanded-row {
    .ant-table-cell:nth-of-type(1) {
      padding: 0
    }
  }

  .innerTable {
    .ant-table-cell {
      padding-left: 64px !important;
    }

    .ant-table-cell:nth-child(3) {
      padding-left: 52px !important;
    }

    .ant-table-cell:nth-child(4) {
      padding-left: 42px !important;
    }

    .ant-table-cell:nth-child(5) {
      padding-left: 30px !important;
    }


  }
}

.openorclose {
  display: flex;
  align-items: center;
}
</style>
<style></style>